// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'test-csp1e'
})
// 1. 连接数据库
const db = cloud.database();
// 2. 获取集合
const stamp = db.collection('stamp');

// 
// 云函数入口函数
exports.main = async(event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID;

  let result = await stamp.where({
    '_openid': openid
  }).get()
  if (result.data.length == 0) {
    result = {
      '_openid': openid,
      'count': 6,
      'date':new Date(),
      'cards': [{
          type: 0,
          number: 0,
          words: '邮家贷'
        },
        {
          type: 1,
          number: 0,
          words: '邮薪贷'
        },
        {
          type: 2,
          number: 0,
          words: '邮学贷'
        },
        {
          type: 3,
          number: 0,
          words: '邮掌柜'
        }
      ]
    }
    await stamp.add({
      data: result
    })
  } else {
    result = result.data[0]
  }

  return {
    result
  }
}